<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {
	
	function User()
	{
		parent::__construct();
		// load language file
		$this->lang->load('i18n');
		$this->load->helper('url');
		
		$this->checkLoggedUser();
	}
	
	public function error(){
		$data = array();
		$data['content'] = $this->load->view('error-content.phtml', null, true);
		$this->load->view('mainpage.phtml', $data);
	}
	
	public function index(){
		$data = array();
		$user = $this->session->userdata("user");
		$user_data = array('name' => $user->NAME, 'password' => $user->PASSWORD);
		
		$data['content'] = $this->load->view('user-content.phtml', $user_data, true);
		$this->load->view('mainpage.phtml', $data);
	}
	
	public function edit(){
		$user = $this->session->userdata("user");
		$user->NAME = $_POST['name'];
		$user->PASSWORD = $_POST['newpassword'];
		
		$this->db->trans_start(true);
		$this->db->where('USER_ID', $user->USER_ID);
		$this->db->update('user', $user);
		$this->db->trans_complete();
		if ($this->db->trans_status() === FALSE)
		{
			$this->session->set_flashdata("errors", array($this->lang->line('lang.edit.user.error')));
			redirect($this->lang->languageCode().'/user/error', 'location');
		}

		// Update new user info to session.
		$this->session->set_userdata("user", $user);
		
		// Redirect and show the number of rows is inserted.
		$this->session->set_flashdata("message", $this->lang->line('lang.edit.user.success'));
		redirect($this->lang->languageCode().'/user/', 'location');
	}
	
	public function checkLoggedUser(){
		$logged_in = $this->session->userdata("loggedIn");
		if(empty($logged_in) && $this->router->fetch_method() != 'error'){
			$this->session->set_flashdata("errors", array($this->lang->line('lang.search.logginRequired')));
			redirect($this->lang->languageCode().'/user/error', 'location');
		}
		return true;
	}
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/user.php */